package org.example.compressor;

import org.example.tool.HuffmanTree;
import org.example.tool.HuffmanTreeInputStream;

import java.io.*;

public class DecompressInputStream {

    private InputStream inputStream;

    public DecompressInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String readAll() throws IOException {

        int length = new DataInputStream(inputStream).readInt();
        if(length == 0) return "";

        HuffmanTreeInputStream huffmanTreeReader = new HuffmanTreeInputStream(inputStream);
        HuffmanTree tree = huffmanTreeReader.readTree();

        StringBuilder builder = new StringBuilder();
        HuffmanTree.Node node = tree.getRoot();
        int r;
        while((r = inputStream.read()) != -1){
            byte b = (byte)r;
            for(int i = 0; i<8; i++) {
                if(b < 0) {
                    node = node.getOne();
                } else {
                    node = node.getZero();
                }
                if(node.isLeaf()) {
                    builder.append(node.getChar());
                    node = tree.getRoot();
                    if(builder.length() == length) {
                        return builder.toString();
                    }
                }
                b <<= 1;
            }
        }
        throw new IOException();
    }

    public void close() throws IOException {
        this.inputStream.close();
    }

}
